package com.tianji.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.api.client.remark.RemarkClient;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.ReplyDTO;
import com.tianji.learning.domain.po.InteractionQuestion;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.domain.vo.ReplyVO;
import com.tianji.learning.enums.QuestionStatus;
import com.tianji.learning.mapper.InteractionQuestionMapper;
import com.tianji.learning.mapper.InteractionReplyMapper;
import com.tianji.learning.query.ReplyPageQuery;
import com.tianji.learning.service.IInteractionReplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 互动问题的回答或评论 服务实现类
 * </p>
 *
 * @author Aimer
 * @since 2025-11-10
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class InteractionReplyServiceImpl extends ServiceImpl<InteractionReplyMapper, InteractionReply> implements IInteractionReplyService {

    private final InteractionQuestionMapper interactionQuestionMapper;
    private final UserClient userClient;
    private final InteractionReplyMapper interactionReplyMapper;
    private final RemarkClient remarkClient;
    private final RabbitMqHelper rabbitMqHelper;
    @Override
    @Transactional
    public void addReply(ReplyDTO replyDTO) {
        // 判断回答的问题是否被删除或者隐藏
        InteractionQuestion interactionQuestion = interactionQuestionMapper.selectById(replyDTO.getQuestionId());
        log.info("问题信息:{}",interactionQuestion);
        if (interactionQuestion == null || interactionQuestion.getHidden()){
            throw new BadRequestException("您要回答的问题已经被删除或者隐藏");
        }
        InteractionReply reply = BeanUtils.copyBean(replyDTO, InteractionReply.class);
        // 获取当前登录用户id
        Long userId = UserContext.getUser();
        reply.setUserId(userId);
        boolean saveSuccess = save(reply);
        if (!saveSuccess){
            throw new BadRequestException("新增回答失败");
        }
        // 判断是否是回答
        if (replyDTO.getAnswerId() == 0){
            // 问题表中回答次数加1
            interactionQuestion.setAnswerTimes(interactionQuestion.getAnswerTimes()+1);
            // 设置最新一个回答的id
            interactionQuestion.setLatestAnswerId(reply.getId());
            // 发送消息队列给当前回答的这个用户添加积分
            if (replyDTO.getIsStudent()){
                rabbitMqHelper.send(MqConstants.Exchange.LEARNING_EXCHANGE,MqConstants.Key.WRITE_REPLY,userId);
            }
        }else {
            // 是评论
            // 回答下的评论数量+1
            // 首先检查该条评论指向的是否是回答如果是则在回答的评论数字段加一
            Long targetReplyId = replyDTO.getTargetReplyId();
            InteractionReply targerinteractionReply = getById(targetReplyId);
            if (targerinteractionReply.getAnswerId() == 0){
                targerinteractionReply.setReplyTimes(targerinteractionReply.getLikedTimes() + 1);
                updateById(targerinteractionReply);
            }
        }

        // 判断回答或者评论是否是学生提交的
        if (replyDTO.getIsStudent()){
            // 将老师管理端的状态对这个问题设置成未查看
            interactionQuestion.setStatus(QuestionStatus.UN_CHECK);
        }
        interactionQuestionMapper.updateById(interactionQuestion);
    }

    @Override
    public PageDTO<ReplyVO> pageReply(ReplyPageQuery replyPageQuery) {
        Page<InteractionReply> page = getPageInteractionReply(replyPageQuery);
        List<InteractionReply> records = page.getRecords();
        if (CollUtils.isEmpty(records)){
            return PageDTO.empty(page);
        }
        // 🔥 新增：获取所有【答案评论】的普通评论数量（只针对 answer_id = 0 的）
        Map<Long, Integer> answerCommentCountMap = new HashMap<>();
        List<Long> answerIds = records.stream()
                .filter(reply -> reply.getAnswerId() != null && reply.getAnswerId() == 0 && !reply.getHidden())
                .map(InteractionReply::getId)
                .collect(Collectors.toList());

        if (!answerIds.isEmpty()) {
            // 调用你刚写的 SQL 方法（返回 List<Map<String, Object>> 或自定义 DTO）
            List<Map<String, Object>> countList = interactionReplyMapper.getAnswerUnderCommentNumber(answerIds);
            for (Map<String, Object> item : countList) {
                Long answerId = (Long) item.get("answer_comment_id");
                Integer count = ((Number) item.get("ordinary_comment_count")).intValue();
                answerCommentCountMap.put(answerId, count);
            }
        }

        // 查询当前登录用户是否对评论或回答点赞了
        List<Long> interactionReplyIds = records.stream().map(InteractionReply::getId).collect(Collectors.toList());
        Set<Long> liked = remarkClient.isBizLiked(interactionReplyIds);
        if (CollUtils.isEmpty(liked)){
            liked = Collections.emptySet();
        }
        // 获取评论人回答人信息
        Map<Long, UserDTO> userMap = getLongUserDTOMap(records);

        List<ReplyVO> replyVOList = new ArrayList<>();
        for (InteractionReply record : records) {
            ReplyVO replyVO = BeanUtils.copyBean(record, ReplyVO.class);
            replyVOList.add(replyVO);

            // 🔥 设置评论数量（仅对答案评论）
            if (record.getAnswerId() != null && record.getAnswerId() == 0) {
                replyVO.setReplyTimes(answerCommentCountMap.getOrDefault(record.getId(), 0));
            } else {
                replyVO.setReplyTimes(0); // 普通评论不显示数量（或按需处理）
            }
            // 判断当前登录用户是否对该内容评论或答复点赞了
            replyVO.setLiked(liked.contains(record.getId()));
            // 判断是否匿名
            if (record.getAnonymity()){
                continue;
            }
            UserDTO userDTO = userMap.get(record.getUserId());
            replyVO.setUserName(userDTO.getName());
            replyVO.setUserIcon(userDTO.getIcon());
            // 获取目标用户信息
            // 根据目标用户评论或者回复的id去找这个目标用户是否匿名
            Long targetReplyId = record.getTargetReplyId();
            InteractionReply targetReply = getById(targetReplyId);
            log.info("目标用户信息:{}",targetReply);
            UserDTO targetUserDTO = userMap.get(record.getTargetUserId());
            if (targetUserDTO != null && targetReply != null && !targetReply.getAnonymity()){
                replyVO.setTargetUserName(targetUserDTO.getName());
            }
        }
        return PageDTO.of(page,replyVOList);
    }

    @Override
    public PageDTO<ReplyVO> adminPageReply(ReplyPageQuery replyPageQuery) {
        Page<InteractionReply> page = getPageInteractionReply(replyPageQuery);
        List<InteractionReply> records = page.getRecords();
        if (CollUtils.isEmpty(records)){
            return PageDTO.empty(page);
        }
        // 获取评论人回答人信息
        Map<Long, UserDTO> userMap = getLongUserDTOMap(records);
        List<ReplyVO> replyVOList = new ArrayList<>();
        for (InteractionReply record : records) {
            ReplyVO replyVO = BeanUtils.copyBean(record, ReplyVO.class);
            replyVOList.add(replyVO);
            UserDTO userDTO = userMap.get(record.getUserId());
            replyVO.setUserName(userDTO.getName());
            replyVO.setUserIcon(userDTO.getIcon());
            // 获取目标用户信息
            UserDTO targetUserDTO = userMap.get(record.getTargetUserId());
            log.info("目标用户信息:{}",targetUserDTO);
            if (targetUserDTO != null){
                replyVO.setTargetUserName(targetUserDTO.getName());
            }
        }
        return PageDTO.of(page,replyVOList);
    }

    @Override
    @Transactional
    public void setReplyHiddenStatus(Long id, Boolean hidden) {
        // 判断该回复是否存在
        InteractionReply interactionReply = getById(id);
        if (interactionReply == null){
            throw new RuntimeException("该回复已经被删除了");
        }

        // 设置隐藏状态（使用传入的 hidden 值！）
        interactionReply.setHidden(hidden);
        updateById(interactionReply);
        // 判断需要隐藏的是回复还是评论
        if (interactionReply.getAnswerId() == 0){
            LambdaUpdateWrapper<InteractionReply> childUpdateWrapper = new LambdaUpdateWrapper<>();
            childUpdateWrapper.eq(InteractionReply::getAnswerId, id)
                    .set(InteractionReply::getHidden, hidden);
            update(childUpdateWrapper); // 批量更新子评论
        }
    }

    private Map<Long, UserDTO> getLongUserDTOMap(List<InteractionReply> records) {
        Set<Long> userIds = new HashSet<>();
        for (InteractionReply record : records) {
            userIds.add(record.getUserId());
        }
        List<UserDTO> users = userClient.queryUserByIds(userIds);
        Map<Long, UserDTO> userMap = new HashMap<>(users.size());
        if (CollUtils.isNotEmpty(users)){
            userMap = users.stream().collect(Collectors.toMap(UserDTO::getId, u -> u));
        }
        return userMap;
    }

    private Page<InteractionReply> getPageInteractionReply(ReplyPageQuery replyPageQuery){
        return lambdaQuery()
                .eq(replyPageQuery.getAnswerId() != null, InteractionReply::getAnswerId, replyPageQuery.getAnswerId())
                .eq(replyPageQuery.getQuestionId() != null, InteractionReply::getQuestionId, replyPageQuery.getQuestionId())
                .page(replyPageQuery.toMpPageDefaultSortByCreateTimeDesc());
    }


}
